package com.basker.pisces.oss.service;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.basker.pisces.oss.model.ObjectMeta;

/**
 * @author hangwen
 * @date 2020/12/12
 */
//TODO 该bean后续应当以autoconfig的方式默认加载
@Component
public class FileSystemOSSService implements OSSService {

    private static final String ROOT = System.getProperty("user.dir") + File.separator + "oss";
    private static final String DEFAULT_CONTAINER = "common";

    @Override
    public ObjectMeta getMeta(final String path) {
        File file = new File(ROOT + File.separator + path);
        if (!file.exists()) {
            return null;
        }

        return new ObjectMeta(file.getName(), path, OSSUtils.generateDownloadUrl(path));
    }

    @Override
    public Resource getResource(final String path) {
        File file = new File(ROOT + File.separator + path);
        if (!file.exists()) {
            return null;
        }

        return new FileSystemResource(file);
    }

    @Override
    public ObjectMeta upload(String container, String name, byte[] data) throws IOException {
        String path = OSSUtils.generatePath(this.resolveContainer(container), name);
        File file = new File(ROOT + File.separator + path);

        FileUtils.writeByteArrayToFile(file, data);

        return new ObjectMeta(name, path, OSSUtils.generateDownloadUrl(path));
    }

    private String resolveContainer(final String container) {
        if (StringUtils.isEmpty(container)) {
            return DEFAULT_CONTAINER;
        } else {
            return container;
        }
    }
}
